package cn.imvc.app.models;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
public class SendMailModelImpl implements SendMailModel {

	private Logger logger = Logger.getLogger(SendMailModelImpl.class);
	@Autowired
	private JavaMailSender javaMailSender;

	public Map<String, String> sendEmail(String to, String subject, String content) {
		Map<String, String> result = new HashMap<String, String>();
		MimeMessage mime = javaMailSender.createMimeMessage();
		MimeMessageHelper helper;
        try {
        	System.setProperty("mail.mime.charset","UTF-8");
        	mime.setHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
        	mime.setHeader("X-Priority", "3");
        	helper = new MimeMessageHelper(mime, true, "UTF-8");
        	InternetAddress fromAddress=null;
			try {
				fromAddress = new InternetAddress(((JavaMailSenderImpl)javaMailSender).getUsername(),"星昊商城","UTF-8");
				helper.setFrom(fromAddress);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

        	helper.setTo(to);
        	helper.setSentDate(new Date());
        	
        	helper.setSubject(subject);
        	helper.setText(content);
        	javaMailSender.send(mime);
        	result.put("code", "1");
        	result.put("msg", "发送成功");
        	logger.info("【发送邮件】 ：[收件人：" + to + ",主题：" + subject + ",内容：" + content + "]");
        	return result;
        } catch (MessagingException me) {
            me.printStackTrace();
        }
    	result.put("code", "0");
    	result.put("msg", "发送失败");
    	return result;
	}

}
